package com.lemon.smartsafety.ui.activity.safe.inspection;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ldzs.recyclerlibrary.view.SpacesItemDecoration;
import com.lemon.android.http.HttpUtils;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.DataInfo;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.EvidenceDataI;
import com.lemon.smartsafety.entity.event.common.HorizontalEvidenceEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.inspection.InspectionCheckItemDetailRefreshEvent;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingCheckItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingIndexVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingItemCountVo;
import com.lemon.smartsafety.entity.safe.company.CompanyBuildingVo;
import com.lemon.smartsafety.entity.safe.inspection.FireCheckLastDetailVo;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.InspectionServices;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.adapter.common.HorizontalEvidenceAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.DrawableUtils;
import com.lemon.smartsafety.utils.common.LemonFileHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 安全巡查 安全巡查【检查项目详情】
 */
public class CheckItemDetailActivity extends SwipeBackActivity {
    @Bind(R.id.metCheckItemTitle)
    MaterialEditText metCheckItemTitle;
    @Bind(R.id.metCheckCycle)
    MaterialEditText metCheckCycle;
    @Bind(R.id.metIsPortal)
    MaterialEditText metIsPortal;
    @Bind(R.id.metLastCheck)
    MaterialEditText metLastCheck;
    @Bind(R.id.iv_status_light)
    CircleImageView  ivStatusLight;
    @Bind(R.id.metCheckRemark)
    MaterialEditText metCheckRemark;
    @Bind(R.id.metHandleRemark)
    MaterialEditText metHandleRemark;


    @Bind(R.id.rippleRepair)
    LinearLayout rippleRepair;
    @Bind(R.id.tv_repair)
    TextView   tvRepair;


    private LoggerHelper loggerHelper = new LoggerHelper(CheckItemDetailActivity.class);


    Drawable statusLightSrc = null;

    /**
     * bundle info
     */
    private CompanyBuildingVo          mCompanyBuildingVo;
    private CompanyBuildingIndexVo     mCompanyBuildingIndexVo;
    private CompanyBuildingItemCountVo mCompanyBuildingItemCountVo;
    private CompanyBuildingCheckItemVo mCompanyBuildingCheckItemVo;

    private FireCheckLastDetailVo detailVo;


    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    SpacesItemDecoration mItemDecoration;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
            mCompanyBuildingCheckItemVo = (CompanyBuildingCheckItemVo) getIntent().getSerializableExtra(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_check_tiem_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();

        if (null == mCompanyBuildingCheckItemVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
        }
        int spacingInPixels = recyclerView.getContext().getResources().getDimensionPixelSize(R.dimen.item_grid_divider_line);
        mItemDecoration = new SpacesItemDecoration(spacingInPixels);
        recyclerView.addItemDecoration(mItemDecoration);


        statusLightSrc = ivStatusLight.getDrawable();
        getNetData();
    }

    private void getNetData() {
        InspectionServices.init().getInspectionCheckItemDetail(mCompanyBuildingCheckItemVo.getItemId());
    }

    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.safe_title);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(CheckItemDetailActivity.this);

    }

    @Subscribe
    public void onEventMainThread(InspectionCheckItemDetailRefreshEvent event) {
        if (InspectionCheckItemDetailRefreshEvent.class.getName().equals(event.getTag())) {
            getNetData();
        }
    }


    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<FireCheckLastDetailVo> event) {
        if (EventTag.TAG_INSPECTION_CHECK_ITEM_DETAIL.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.hidden();
                    detailVo = event.getObj();
                    handlerViewValue(detailVo);
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }

    private void handlerViewValue(FireCheckLastDetailVo vo) {
        metCheckItemTitle.setText(StringUtils.nullValue(vo.getItemName()));

        metCheckCycle.setText(vo.getCheckValidity());

        if (StringUtils.getBoolean(mCompanyBuildingCheckItemVo.getIsPatrol())) {
            metIsPortal.setText(DataInfo.getStatusString("是", DataInfo.ColorStatus.STATUS_BLUE));
        } else {
            metIsPortal.setText(DataInfo.getStatusString("否", DataInfo.ColorStatus.STATUS_GRAY));
        }
        metLastCheck.setText(vo.getLastCheckUserName() + " " + DateUtils.getFormatDateStringWithDateString(vo.getLastCheckDate(), DateUtils.dateFormatYMDHM));

        String statusString = StringUtils.nullValue(vo.getStatus(), "0");

        if (DataInfo.RED_TAG.equals(statusString)) {
            ivStatusLight.setImageDrawable(DrawableUtils.$tint(statusLightSrc, ivStatusLight.getContext().getResources().getColor(R.color.colorAppRed)));
        } else if (DataInfo.YELLOW_TAG.equals(statusString)) {
            ivStatusLight.setImageDrawable(DrawableUtils.$tint(statusLightSrc, ivStatusLight.getContext().getResources().getColor(R.color.colorAppYellow)));
        } else {
            ivStatusLight.setImageDrawable(DrawableUtils.$tint(statusLightSrc, ivStatusLight.getContext().getResources().getColor(R.color.colorAppGreen)));
        }

        metCheckRemark.setText(StringUtils.nullValue(vo.getCheckRemark()).trim());

        String reportId = StringUtils.nullValue(vo.getReportId());
        if (DataInfo.RED_TAG.equals(statusString) || DataInfo.YELLOW_TAG.equals(statusString)) {
            if (reportId.length() == 0) {
                metHandleRemark.setText(DataInfo.getStatusString("尚未进行报修", DataInfo.ColorStatus.STATUS_RED));
                rippleRepair.setVisibility(View.VISIBLE);
            } else {
                metHandleRemark.setText(DataInfo.getStatusString("已报修", DataInfo.ColorStatus.STATUS_BLUE));
                rippleRepair.setVisibility(View.GONE);
            }
        } else {
            metHandleRemark.setText(DataInfo.getStatusString("已正常结束检查", DataInfo.ColorStatus.STATUS_GREEN));
            rippleRepair.setVisibility(View.GONE);
        }


        /* 这里处理证据材料 */
        List<EvidenceDataI> result = new ArrayList<>();
        result.addAll(vo.getAssetsList());
        if (result.size() != 0) {
            recyclerView.setVisibility(View.VISIBLE);
            /**
             * 证据视图部分
             */
            HorizontalEvidenceAdapter evidenceAdapter = new HorizontalEvidenceAdapter(result);
            LinearLayoutManager       layoutManager   = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.setAdapter(evidenceAdapter);
        } else {
            recyclerView.setVisibility(View.GONE);
        }

    }


    /**
     * 查看照片
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HorizontalEvidenceEvent event) {
        List<EvidenceDataI> res = event.getData();
        if (res != null && res.size() != 0) {
            EvidenceDataI data = res.get(event.getPosition());
            if (LemonFileHelper.isImageUrl(data.getEvidenceUrl())) {
                List<PhotoInfo> photos = HorizontalEvidenceAdapter.getPhotoInfoList(event.getData());
                if (photos != null && photos.size() != 0) {
                    UIHelper.showPhotoView(this, photos, event.getPosition());
                }
            } else if (LemonFileHelper.isVoiceUrl(data.getEvidenceUrl())) {
                playVoice(HttpUtils.formatFilesUrl(data.getEvidenceUrl()));
            }
        }
    }


    @OnClick({R.id.rippleRepair})
    public void onClickAction(View view) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        bundle.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, mCompanyBuildingCheckItemVo);
        bundle.putString(BundleKey.SAFE_INSPECTION_CHECK_ID, detailVo.getCheckId());
        UIHelper.showActivity(this, bundle, CheckItemRepairActivity.class);
    }


    /****************************************************************************************************************
     * 保护现场
     ****************************************************************************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(BundleKey.COMPANY_BUILD_INFO, mCompanyBuildingVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT, mCompanyBuildingItemCountVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO, mCompanyBuildingIndexVo);
        outState.putSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO, mCompanyBuildingCheckItemVo);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            mCompanyBuildingVo = (CompanyBuildingVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILD_INFO);
            mCompanyBuildingIndexVo = (CompanyBuildingIndexVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_INDEX_VO);
            mCompanyBuildingItemCountVo = (CompanyBuildingItemCountVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_ITEM_COUNT);
            mCompanyBuildingCheckItemVo = (CompanyBuildingCheckItemVo) savedInstanceState.getSerializable(BundleKey.COMPANY_BUILDING_CHECK_ITEM_VO);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_INSPECTION_CHECK_ITEM_RECORD);
        mCompanyBuildingVo = null;
        mCompanyBuildingIndexVo = null;
        mCompanyBuildingItemCountVo = null;
        mCompanyBuildingCheckItemVo = null;
    }
}
